package cn.jesin.ssmss01.handler;

import cn.jesin.ssmss01.common.Flag;
import cn.jesin.ssmss01.vo.responseformat.Code;
import cn.jesin.ssmss01.vo.responseformat.Result;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author 谷汉斌
 * @description 权限拒绝处理器
 * @createTime 2024/7/31 下午3:34
 */
@Component
public class RestAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        ServletOutputStream outputStream = response.getOutputStream();
        Result<Object> result = Result.builder()
                .flag(Flag.FAIL.isCode())
                .code(Code.DENIED.getCode())
                .message("该请求已拒绝！").build();
        String s = JSON.toJSONString(result);
        outputStream.write(s.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
